package com.zzyl.framework.interceptor.member;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocalUtil;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信端拦截器
 *
 * @author yhy
 */

@Configuration
public class MemberInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MemberInterceptor.class);
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        log.info("进入拦截器···");
        log.info("正在获取token···");
        // 获取token
        String token = request.getHeader("authorization");
        // 判断token是否为空
        if(StringUtils.isEmpty(token)){
            // token为空 响应401
            response.setStatus(401);
            throw new BaseException("用户还未登录, 请先登录");
        }

        log.info("token: {} ",  token);
        log.info("正在解析token···");
        // token有值 检验token
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            throw new BaseException("token 解析失败");
        }

        log.info("解析token成功, 正在获取用户信息···");
        if(ObjectUtil.isEmpty( claims)){
            // token非法 响应401
            response.setStatus(401);
            throw new BaseException("获取用户信息失败！");
        }

        // token有效 获取token中的用户信息
        // 用户id
        Long id = MapUtil.getLong(claims, "id");
        // 用户名
        String username = MapUtil.getStr(claims, "nickName");

        log.info("用户id: {}, 用户名: {}", id, username);
        // 将用户信息保存到ThreadLocal
        UserThreadLocalUtil.setUserId(id);
        UserThreadLocalUtil.setUserName(username);

        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtil.clear();
    }
}
